import { computed, defineComponent, reactive, ref, Teleport, toRaw, unref } from 'vue';
import './index.less';
import { Icon } from '/@/components/Icon';
import { useRouter } from 'vue-router';
import { find, cloneDeep } from 'lodash-es';
import Title from '/@/views/verse/components/Title';
import type { DeckCardItem } from '/@/api/verse/model/deckModel';
import { CardList, CardListQuery, CardType } from '/@/api/verse/model/cardModel';
import { Button, Empty, Field, List, ConfigProvider } from 'vant';
import { awaitWrap, filterNullAttributes, judgeSystem } from '/@/utils';
import { CardListApi } from '/@/api/verse/card';
import BaseSearch from '/@/views/verse/components/CardSearch/BaseSearch';
import SeriesSearch from '/@/views/verse/components/CardSearch/SeriesSearch';
import DeckCardDetail from '/@/views/verse/components/DeckCardDetail/DeckCardDetail';
import { useOptions } from '/@/views/verse/hooks/useOptions';
import { useVerseStore } from '/@/store/modules/verse';
import { useMessage } from '/@/hooks/web/useMessage';
import { appShareUsing } from '/@/utils/appInteractive';
import ChooseCardPopup from './components/ChooseCardPopup';

export default defineComponent({
  name: 'DeckCardPage',
  props: {
    type: {
      type: String as PropType<'main' | 'other'>,
      required: true,
    },
  },
  setup(props) {
    // 设置分享参数
    appShareUsing({} as any);

    const { careerOptions } = useOptions();

    const router = useRouter();
    const { createInfoToast } = useMessage();
    const pageTile = computed(() => {
      const { type } = props;
      if (type === 'main') {
        return '添加主牌';
      }
      return '添加额外牌';
    });
    const leftClick = () => {
      router.back();
    };

    const verseStore = useVerseStore();
    const queryState = reactive<CardListQuery>({
      page: 1,
      page_size: 30,
      message: '',
      rarity: [],
      card_career: [],
      card_category: [],
      mana: [],
      series_id: [],
    });
    // 设置默认职业筛选条件，默认选中已选择的主战者的职业 + 中立职业
    if (verseStore.getCreateDeckParams.main_fighters.length > 0) {
      queryState.card_career?.push(careerOptions[0].value as string);
      verseStore.getCreateDeckParams.main_fighters.map((item) => {
        queryState.card_career?.push(item.card_career!);
      });
    }
    const searchFieldSlot = {
      button: () => {
        return (
          <Button
            type={'primary'}
            size={'small'}
            onClick={() => {
              getList(true);
            }}
          >
            搜索
          </Button>
        );
      },
    };

    // 数据获取
    const listLoading = ref(false); // 是否正在加载中 默认不在加载中，流会去加载数据
    const listFinished = ref(false); // 是否全部数据加载完成
    const listEmpty = ref(false);
    const listData = reactive<CardList>({
      total: 0,
      rows: [],
    });

    /**
     *
     * @param isRefresh 是否重新加载列表
     */
    const getList = async (isRefresh: boolean) => {
      if (isRefresh) {
        queryState.page = 1;
        listLoading.value = true;
        listData.rows = [];
      }
      const params: CardListQuery = filterNullAttributes(queryState, []);
      params.card_type = props.type === 'main' ? CardType.MAIN : CardType.BACKUP;
      const [error, data] = await awaitWrap(CardListApi(toRaw(params)));
      if (error) {
        return;
      }
      const result = data as CardList;
      if (queryState.page === 1) {
        listData.total = result.total;
        listFinished.value = false;
        !result.total ? (listEmpty.value = true) : (listEmpty.value = false);
      }
      for (const item of result.rows) {
        listData.rows.push(item);
      }
      queryState.page += 1;
      listLoading.value = false;
      if (listData.rows.length >= listData.total) {
        listFinished.value = true;
      }
    };
    const GetCardItem = ({ cardList }: { cardList: CardList }) => {
      const listArr: VueNode[] = [];

      const CardAction = ({ card }: { card: DeckCardItem }) => {
        const target = find(selectCards, ['card_id', card.card_id]);
        target ? (card.number = target.number) : (card.number = 0);
        return (
          <ConfigProvider
            themeVars={{ buttonBorderWidth: 0 }}
            class={'card-action-buttons flex justify-between absolute bg-white'}
          >
            <Button
              plain
              icon={'minus'}
              size={'small'}
              type='primary'
              round
              disabled={!card.number}
              onClick={() => {
                delCardClick(card);
              }}
            />
            <span class={`card-nums ${card.number ? '' : 'hidden'}`}>x{card.number}</span>
            <Button
              plain
              icon={'plus'}
              size={'small'}
              type='primary'
              round
              disabled={card.number! >= addRule.maxNum}
              onClick={() => {
                addCardClick(card);
              }}
            />
          </ConfigProvider>
        );
      };

      cardList.rows.map((item) => {
        listArr.push(
          <li class={'card-item relative'}>
            <div class='image'>
              <img
                src={item.img}
                alt=''
                onClick={() => {
                  detailState.value = true;
                  detailCardIdState.value = item.card_id!;
                }}
              />
            </div>
            <div class={'name-box'}>
              <div class={'name-content van-ellipsis text-xs text-white px-md'}>
                [{item.is_foil ? '闪' : '平'}]{item.name}
              </div>
            </div>
            <CardAction card={item} />
          </li>
        );
      });
      return <ul class='card-list flex flex-wrap'>{listArr}</ul>;
    };

    // 筛选Popup
    const searchState = ref(false);
    const seriesPopupState = ref(false);
    // 打开其他条件筛选
    const filterClick = () => {
      searchState.value = true;
    };
    // 打开系列筛选
    const seriesPopupClick = () => {
      seriesPopupState.value = true;
    };

    // 详情
    const detailState = ref(false);
    const detailCardIdState = ref(0);

    // 适配安卓键盘
    const bottomSearchClass = ref('');
    const fieldFocusClick = () => {
      console.log(judgeSystem());
      if (judgeSystem() === 'android') {
        bottomSearchClass.value = 'android';
        return false;
      }
      bottomSearchClass.value = '';
    };
    const fieldBlurClick = () => {
      bottomSearchClass.value = '';
    };

    // 已选择卡牌
    const addRule = {
      // 添加规则：最大张数
      maxNum: 3,
    };
    const selectCards = reactive<DeckCardItem[]>([]);
    const setSelectCard = () => {
      const { type } = props;
      const data =
        type === 'main' ? verseStore.getCreateDeckParams.main_cards : verseStore.getCreateDeckParams.other_cards;
      for (const item of cloneDeep(data)) {
        selectCards.push(item);
      }
    };
    setSelectCard();
    const addCardClick = (card: DeckCardItem) => {
      // 判断规则名称卡牌
      const ruleCardArr: DeckCardItem[] = [];
      selectCards.map((item) => {
        if (item.other_ename === card.other_ename) {
          ruleCardArr.push(item);
        }
      });
      if (ruleCardArr.length > 0) {
        let ruleCardNum = 0;
        for (const c of ruleCardArr) {
          ruleCardNum += c.number || 0;
        }
        if (ruleCardNum >= addRule.maxNum) {
          createInfoToast({ message: '单卡放置已满3张，不能继续添加' });
          return false;
        }
      }

      // 判断同一张卡
      const target = find(selectCards, ['card_id', card.card_id]);
      if (!target) {
        card.number = 1;
        selectCards.push(card);
        return;
      }
      target.number! >= 3 ? console.log('同张卡牌数量不能超过3张') : (target.number! += 1);
    };
    const delCardClick = (card: DeckCardItem) => {
      const target = find(selectCards, ['card_id', card.card_id]);
      if (!target) {
        return;
      }
      target.number! -= 1;
      if (!target.number) {
        let delIndex = 0;
        selectCards.filter((item, index) => {
          if (item.card_id === target.card_id) {
            delIndex = index;
          }
        });
        selectCards.splice(delIndex, 1);
      }
    };
    const confirmAddCards = () => {
      const { type } = props;
      type === 'main'
        ? verseStore.setCreateDeckMainCard(toRaw(selectCards))
        : verseStore.setCreateDeckOtherCard(toRaw(selectCards));
      router.back();
    };
    // 已选择卡牌的浮层
    const chooseShowState = ref(false);

    return () => (
      <div class={'verse-deck-card-page'}>
        <Title title={unref(pageTile)} leftArrow onLeftClick={leftClick} />
        <div class={'card-list-container'}>
          {unref(listEmpty) ? (
            <Empty>未找到相关卡牌</Empty>
          ) : (
            <List
              v-model={[listLoading.value, 'loading']}
              finished={unref(listFinished)}
              finishedText={'没有更多卡牌'}
              onLoad={getList}
            >
              <GetCardItem cardList={listData} />
            </List>
          )}
        </div>
        <div class={`bottom-area flex ${unref(bottomSearchClass)}`}>
          <div class={'bottom-search flex items-center'}>
            <div class={'input-box'}>
              <Field
                v-model={[queryState.message]}
                placeholder='卡牌名称或规则'
                leftIcon={'search'}
                v-slots={searchFieldSlot}
                clearable
                onFocus={fieldFocusClick}
                onBlur={fieldBlurClick}
              />
            </div>
            <div class='svg-button filter text-center' onClick={filterClick}>
              <Icon icon={'single-filter|svg'} size={30} />
              <span class={'block text-sm'}>筛选</span>
            </div>
          </div>
          <Button
            size={'large'}
            type={'primary'}
            class={'add-button'}
            disabled={!selectCards.length}
            onClick={confirmAddCards}
          >
            确认添加
          </Button>
        </div>
        <div
          class={'choose-popup-button'}
          onClick={() => {
            chooseShowState.value = true;
          }}
        >
          查看已选择卡牌
        </div>

        <Teleport to={'body'}>
          <BaseSearch
            v-model={[searchState.value, 'show']}
            queryState={queryState}
            onPageRefresh={() => {
              getList(true);
            }}
            onOpenSeriesPopup={seriesPopupClick}
            isDeck={true}
          />
          <SeriesSearch
            v-model={[seriesPopupState.value, 'show']}
            queryState={queryState}
            onPageRefresh={() => {
              getList(true);
            }}
          />
        </Teleport>
        <DeckCardDetail v-model={[detailState.value, 'show']} cardId={detailCardIdState.value} />
        <ChooseCardPopup
          v-model={[chooseShowState.value, 'show']}
          selectCards={selectCards}
          onAddCard={addCardClick}
          onDelCard={delCardClick}
        />
      </div>
    );
  },
});
